package ch.rouge66.energymonitor;
import ch.rouge66.energymonitor.dao.EnergyLogEntryDao;
import ch.rouge66.energymonitor.dao.EnergyLogEntryDaoImpl;
import ch.rouge66.energymonitor.dao.EntityManager;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;

/**
 * @author Marcel Roth
 * @version V1.0, 23.08.2014
 *
 */
public class EnergyMonitor {
    
    public static void main(String args[]) throws InterruptedException {
    	//
    	System.out.println("Energy Monitor: starting ...");
    	// Initialize
    	EntityManager entityMgr = new EntityManager();
    	EnergyLogEntryDao energyLogEntryDao = new EnergyLogEntryDaoImpl();

    	// create gpio controller
        final GpioController gpio = GpioFactory.getInstance();
        // provision gpio pin #00 (#17) as an input pin with its internal pull down resistor enabled
        final GpioPinDigitalInput optoSwitch = gpio.provisionDigitalInputPin(RaspiPin.GPIO_01, PinPullResistance.PULL_DOWN);
        // create and register gpio pin listener
        GpioPinListenerDigital energyMonitorStateChangeEventListener = new EnergyMonitorStateChangeEventListener(entityMgr, energyLogEntryDao);
		optoSwitch.addListener(energyMonitorStateChangeEventListener);
		//
        System.out.println("Energy Monitor: setup complete ...");
        // keep program running until user aborts (CTRL-C)
        System.out.println("Energy Monitor: listening for events ...");
        for (;;) {
            Thread.sleep(100);
    	}
        // stop all GPIO activity/threads by shutting down the GPIO controller
        // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
        // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO controller        
    }
}
